//index.js
//获取应用实例
const app = getApp();
import httpsUtils from '../../utils/https.js';

var rate = 0; //分辨转换
var floatTop = 0; //悬浮高度
Page({
  data: {
    bannerList: [],
    indicatorDots: true,
    autoplay: true,
    interval: 3000,
    duration: 1000,
    circular: true,
    hourTime: '00', //限时抢购开始时间
    minuteTime: '00',
    secondTime: '00',
    list: [],
    list_total: 0,
    indexList: [],
    // small_nav初始数据
    tabs: [{
        id: "nav_1",
        isSelect: true,
        title: "推荐",
        value: 1,
        isFirst: false
      },
      {
        id: "nav_2",
        isSelect: false,
        title: "上新",
        value: 2,
        isFirst: true
      },
      {
        id: "nav_3",
        isSelect: false,
        title: "关注",
        value: 3,
        isFirst: true
      },
      {
        id: "nav_4",
        isSelect: false,
        title: "低价",
        value: 4,
        isFirst: true
      },
      {
        id: "nav_5",
        isSelect: false,
        title: "中等",
        value: 5,
        isFirst: true
      },
      {
        id: "nav_6",
        isSelect: false,
        title: "高档",
        value: 6,
        isFirst: true
      }
    ], //tabbar数组
    curTabId: "nav_1", //当前tabid
    isShowFloatTab: false, //是否显示悬浮tab

    guessLikeList: [], //推荐猜你喜欢列表
    guessLikeLenght: 1,
    guessCurrent: 1,
    guessHasNextPage: true,

    newsList: [], //上新列表
    newslength: 1,
    newsCurrent: 1,
    newsHasNextPage: true,

    hotList: [], //热卖
    hotLength: 1,
    hotCurrent: 1,
    hotHasNextPage: true,

    lowList: [], //低价排序
    lowLength: 1,
    lowCurrent: 1,
    lowHasNextPage: true,

    modList: [], //中等排序
    modLength: 1,
    modCurrent: 1,
    modHasNextPage: true,

    highList: [], //高价
    highLength:1,
    highCurrent: 1,
    highHasNextPage: true,

    userCode: "",

    pictureList: [], //广告

    noticeTitleArray: [],

    zbList: [], 
    isZb: false, 
    zbWidth: 750,

    toTop:false
  },
  /**
   * 中间轮播图
   */
  setNoticeList: function() {
    var that = this;
    httpsUtils.getData({
      _url: app.globalData._url + '/message/selectMessageList',
      data: {},
    }, function(json) {
      if (json.data && json.success) {
        that.setData({
          noticeTitleArray: json.data,
        })
      }
    })
  },
  /**
   * 中间轮播图
   */
  getEachPictureList: function() {
    var that = this;
    httpsUtils.getData({
      _url: app.globalData._url + '/eachPicture/getEachPictureList?type=13&sort=2',
      data: {},
    }, function(json) {
      for (let obj of json.data) {
        if (obj.auctionType == 1) {
          obj.auctionHttpUrl = '/pages/shopInformation/shopInformation?shopid=' + obj.auctionId
        }
        if (obj.auctionType == 2) {
          obj.auctionHttpUrl = '/pages/productDetail/productDetail?id=' + obj.auctionId
        }
        if (obj.auctionType == 3) {
          obj.auctionHttpUrl = '/pages/webhtml/webhtml?url=' + encodeURIComponent(obj.auctionHttpUrl)
        }
      }
      if (json.data && json.success) {
        that.setData({
          pictureList: json.data,
        })
      } 
    })
  },
  /**
   * 获取店铺商品
   */
  getShopGoods: function(e) {
    var that = this;
    var nowTab = 1;
    for (let obj of that.data.tabs) {
      if (obj.isSelect) {
        nowTab = obj.value;
      }
    }

    var shopId = that.data.shopId;
    var goodsType = '';
    var sort = '';
    var current = 1;

    //推荐
    if (nowTab == 1) {
      goodsType = 1;
      sort = 2;
      current = that.data.guessCurrent
    }
    //上新
    if (nowTab == 2) {
      goodsType = 2;
      sort = 2;
      current = that.data.newsCurrent
    }
    //关注
    if (nowTab == 3) {
      goodsType = '';
      sort = 7;
      current = that.data.hotCurrent
    }
    //低价
    if (nowTab == 4) {
      goodsType = '';
      sort = 4;
      current = that.data.lowCurrent
    }
    //中等
    if (nowTab == 5) {
      goodsType = '';
      sort = 8;
      current = that.data.modCurrent
    }
    //高档
    if (nowTab == 6) {
      goodsType = '';
      sort = 3;
      current = that.data.highCurrent
    }

    that.getData({
      _url: app.globalData._url + '/goods/selectIndexGoodsList?goodsType=' + goodsType + "&sort=" + sort + "&current=" + current,
      data: {},
    }, function(json) {
      if (json.data && json.success) {
        //推荐
        if (nowTab == 1) {
          that.setData({
            guessLikeList: that.data.guessLikeList.concat(json.data.list),
            guessLikeLenght: json.data.total,
            guessCurrent: json.data.pageNum,
            guessHasNextPage: json.data.hasNextPage,
          })
        }
        //上新
        if (nowTab == 2) {
          that.setData({
            newsList: that.data.newsList.concat(json.data.list),
            newsLength: json.data.total,
            newsCurrent: json.data.pageNum,
            newsHasNextPage: json.data.hasNextPage,
          })
        }
        //关注
        if (nowTab == 3) {
          that.setData({
            hotList: that.data.hotList.concat(json.data.list),
            hotLength: json.data.total,
            hotCurrent: json.data.pageNum,
            hotHasNextPage: json.data.hasNextPage,
          })
        }
        //低价
        if (nowTab == 4) {
          that.setData({
            lowList: that.data.lowList.concat(json.data.list),
            lowLength: json.data.total,
            lowCurrent: json.data.pageNum,
            lowHasNextPage: json.data.hasNextPage,
          })
        }
        //中等
        if (nowTab == 5) {
          that.setData({
            modList: that.data.modList.concat(json.data.list),
            modLength: json.data.total,
            modCurrent: json.data.pageNum,
            modHasNextPage: json.data.hasNextPage,
          })
        }
        //高档
        if (nowTab == 6) {
          that.setData({
            highList: that.data.highList.concat(json.data.list),
            highLength: json.data.total,
            highCurrent: json.data.pageNum,
            highHasNextPage: json.data.hasNextPage,
          })
        }
      } else {
        console.log("请求失败")
      }
    })
  },
  /**
   * 下拉刷新
   */
  goodPullDown: function() {
    var that = this;
    var nowTab = 1;
    for (let obj of that.data.tabs) {
      if (obj.isSelect) {
        nowTab = obj.value;
      }
    }
    //推荐
    if (nowTab == 1) {
      if (that.data.guessHasNextPage) {
        that.setData({
          guessCurrent: that.data.guessCurrent + 1,
        })
        that.getShopGoods();
      }
    }
    //上新
    if (nowTab == 2) {
      if (that.data.newsHasNextPage) {
        that.setData({
          newsCurrent: that.data.newsCurrent + 1,
        })
        that.getShopGoods();
      }
    }
    //关注
    if (nowTab == 3) {
      if (that.data.hotHasNextPage) {
        that.setData({
          hotCurrent: that.data.hotCurrent + 1,
        })
        that.getShopGoods();
      }
    }
    //低价
    if (nowTab == 4) {
      if (that.data.lowHasNextPage) {
        that.setData({
          lowCurrent: that.data.lowCurrent + 1,
        })
        that.getShopGoods();
      }
    }
    //中等
    if (nowTab == 5) {
      if (that.data.modHasNextPage) {
        that.setData({
          modCurrent: that.data.modCurrent + 1,
        })
        that.getShopGoods();
      }
    }
    //高价
    if (nowTab == 6) {
      if (that.data.highHasNextPage) {
        that.setData({
          highCurrent: that.data.highCurrent + 1,
        })
        that.getShopGoods();
      }
    }
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    var that = this;
    
    //that.findZbList();

    that.getScrollTop();

    //下单信息滚动
    that.setNoticeList();

    /*首页轮播图片*/
    that.getData({
      _url: app.globalData._url + '/eachPicture/selectEachPictureListByType?type=12',
      data: '',
    }, function(json) {
      if (json.data && json.success) {
        for (let obj of json.data){
          if (obj.auctionType == 1){
            obj.auctionHttpUrl = '/pages/shopInformation/shopInformation?shopid=' + obj.auctionId
          }
          if (obj.auctionType == 2) {
            obj.auctionHttpUrl = '/pages/productDetail/productDetail?id=' + obj.auctionId
          } 
          if (obj.auctionType == 3) {
            obj.auctionHttpUrl = '/pages/webhtml/webhtml?url=' + encodeURIComponent(obj.auctionHttpUrl)
          } 
        }
        that.setData({
          bannerList: json.data
        })
      }
    });

    /*首页商家求购，厂家尾货图片请求*/
    that.getData({
      _url: app.globalData._url + '/advertissing/selectAlls',
      data: '',
    }, function(json) {
      if (json.data && json.success) {
        var indexList = ['', '', '', '', ''];
        for (let obj of json.data) {
          if (obj.Advertising_id == 1) {
            indexList[0] = obj.Advertising_urls;
          }
          if (obj.Advertising_id == 2) {
            indexList[1] = obj.Advertising_urls;
          }
          if (obj.Advertising_id == 3) {
            indexList[2] = obj.Advertising_urls;
          }
          if (obj.Advertising_id == 18) {
            indexList[3] = obj.Advertising_urls;
          }
          if (obj.Advertising_id == 27) {
            indexList[4] = obj.Advertising_urls;
          }
        }
        that.setData({
          indexList: indexList,
        })
      }
    });

    /*限时抢购距离结束时间*/
    that.getData({
      _url: app.globalData._url + '/rushTime/getRushTime',
      data: '',
    }, function (json) {
      that.cutdown(json);
    })
    /*商圈数据请求*/
    that.getData({
      _url: app.globalData._url + '/tradeArea/selectList1?size=5&current=1',
      data: '',
    }, function(json) {
      if (json.data && json.success) {
        that.setData({
          list: json.data.list,
          list_total: json.data.total
        })
      }
    })
   

    //获取商品列表
    this.getShopGoods();

    //获取广告位
    this.getEachPictureList();

  },
  cutdown:function(json){
    var that = this;
    var endTime = '';
    var startTime = '';
    if (json.data != null) {
      endTime = json.data.endTime;
      startTime = json.data.startTime;
    }

    var new_date = new Date();
    var years = new_date.getFullYear(); // 获取完整的年份(4位,1970-????)
    var month = ("0" + (new_date.getMonth() + 1)).slice(-2); // 获取当前月份(0-11,0代表1月)
    var days = new_date.getDate(); // 获取当前日(1-31)
    var new_date_times = new_date.getTime(); // 获取当前时间(从1970.1.1开始的毫秒数)
    var currentTimes = years + "/" + month + "/" + days;
    var end_times = currentTimes +' '+ endTime; // 限时抢购结束时间
    var start_times = currentTimes + ' ' + startTime; //限时抢购开始时间
    var zero_times = currentTimes + ' ' + '00' + ':' + '00' + ':' + '00'; //当日00：00:00时间
    var zero_date_times = new Date(zero_times).getTime(); //获取毫秒值
    var start_date_times = new Date(start_times).getTime();
    if (json.data && json.success) {
      if (zero_date_times <= new_date_times <= start_date_times) {
        var diff_time = Math.floor((start_date_times - zero_date_times) / 1000);
        setTimeout(function () {
          that.cutdown(json)
        }, 1000)
        var hour_time = ("0" + Math.floor(diff_time / 3600 % 24)).slice(-2);
        var minute_time = ("0" + Math.floor(diff_time / 60 % 60)).slice(-2);
        var second_time = ("0" + Math.floor(diff_time % 60)).slice(-2);
        that.setData({
          hourTime: hour_time,
          minuteTime: minute_time,
          secondTime: second_time,
        })
      } else {
        that.setData({
          hourTime: "00",
          minuteTime: "00",
          secondTime: "00",
        })
      }
      that.setData({
        limitDeta: json.data,
      })
    }
  },
  //事件函数
  //search 搜索
  searchs: function() {
    wx.navigateTo({
      url: '../search/search',
    })
  },
  // ask to buy 商家求购
  toBuy: function() {
    wx.navigateTo({
      url: '../askToBuy/askToBuy',
    })
  },
  // leftover Stock 厂家尾货
  stoc: function() {
    wx.navigateTo({
      url: '../leftoverStock/leftoverStock',
    })
  },
  //限时抢购
  limitBuy: function() {
    wx.navigateTo({
      url: '../limitBuy/limitBuy',
    })
  },
  // 品牌大本营
  brand: function() {
    wx.navigateTo({
      url: '../brand/brand',
    })
  },
  //  更多商圈
  moreBusiness: function() {
    wx.navigateTo({
      url: '../moreBusinessCircle/moreBusinessCircle',
    })
  },
  /**
   * 全国上新
   */
  newPro: function() {
    wx.navigateTo({
      url: '../askToNew/askToNew',
    })
  },

  
  findZbList: function() {
    var that = this;
    httpsUtils.getData({
      _url: app.globalData._url + '/liveBroadcastOpen/selectList?type=1',
      data: {},
    }, function(json) {
      if (json.data && json.success) {
        var live = json.data.liveBroadcastOpen;
        if (live.isOpen == 0) {
          that.setData({
            isZb: true,
          })
          httpsUtils.getData({
            _url: app.globalData._url + '/zbDirectSeeding/xcxZbDirectSeedingList',
            data: {},
          }, function(json) {
            if (json.data && json.success) {
              that.setData({
                zbList: json.data,
                zbWidth: json.data.length * 211,
              })
            }
            /** small nav */
            that.getScrollTop();
          })
        }else{
          /** small nav */
          that.getScrollTop();
        }
      }
    })
  },
  /**
   * 提示
   */
  // zbTip: function(e) {
  //   wx.showModal({
  //     title: '预告',
  //     content: '本场时间:\r\n'+ e.currentTarget.dataset.time,
  //     showCancel: false,
  //   })
  // },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {
    this.setData({
      bannerList: [],
      indicatorDots: true,
      autoplay: true,
      interval: 3000,
      duration: 1000,
      circular: true,
      hourTime: '00', //限时抢购开始时间
      minuteTime: '00',
      secondTime: '00',
      list: [],
      list_total: 0,
      indexList: [],
      // small_nav初始数据
      tabs: [{
        id: "nav_1",
        isSelect: true,
        title: "推荐",
        value: 1,
        isFirst: false
      },
      {
        id: "nav_2",
        isSelect: false,
        title: "上新",
        value: 2,
        isFirst: true
      },
      {
        id: "nav_3",
        isSelect: false,
        title: "关注",
        value: 3,
        isFirst: true
      },
      {
        id: "nav_4",
        isSelect: false,
        title: "低价",
        value: 4,
        isFirst: true
      },
      {
        id: "nav_5",
        isSelect: false,
        title: "中等",
        value: 5,
        isFirst: true
      },
      {
        id: "nav_6",
        isSelect: false,
        title: "高档",
        value: 6,
        isFirst: true
      }
      ], //tabbar数组
      curTabId: "nav_1", //当前tabid
      isShowFloatTab: false, //是否显示悬浮tab

      guessLikeList: [], //推荐猜你喜欢列表
      guessLikeLenght: 1,
      guessCurrent: 1,
      guessHasNextPage: true,

      newsList: [], //上新列表
      newslength: 1,
      newsCurrent: 1,
      newsHasNextPage: true,

      hotList: [], //热卖
      hotLength: 1,
      hotCurrent: 1,
      hotHasNextPage: true,

      lowList: [], //低价排序
      lowLength: 1,
      lowCurrent: 1,
      lowHasNextPage: true,

      modList: [], //中等排序
      modLength: 1,
      modCurrent: 1,
      modHasNextPage: true,

      highList: [], //高价
      highLength: 1,
      highCurrent: 1,
      highHasNextPage: true,

      userCode: "",

      pictureList: [], //广告

      noticeTitleArray: [],

      zbList: [],
      isZb: false,
      zbWidth: 750,

      toTop: false
    })

    this.onLoad();
    wx.stopPullDownRefresh(); 
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {
    this.goodPullDown();
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  },
  //banner
  changeIndicatorDots: function(e) {
    this.setData({
      indicatorDots: !this.data.indicatorDots
    })
  },
  changeAutoplay: function(e) {
    this.setData({
      autoplay: !this.data.autoplay
    })
  },
  intervalChange: function(e) {
    this.setData({
      interval: e.detail.value
    })
  },
  durationChange: function(e) {
    this.setData({
      duration: e.detail.value
    })
  },
  /*small nav*/
  /**
   * 获得滑动导致悬浮开始的高度
   * @return {[type]} [description]
   */
  getScrollTop: function() {
    var that = this;
    //var isZb = that.data.isZb;
    //var zbList = that.data.zbList;
    var floatSize = 2404;
    // if (isZb && zbList.length > 0) {
    //   floatSize = 2772;
    // }

    if (wx.getSystemInfo) {
      wx.getSystemInfo({
        success: function(res) {
          rate = res.screenWidth / 750;
          floatTop = floatSize * rate;
          that.setData({            
            scrollTop: floatSize * res.screenWidth / 750,
            scrollHeight: res.screenHeight / (res.screenWidth / 750) - 128,
          });
        }
      });
    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onPageScroll: function(event) {
    var scrollTop = event.scrollTop;
    if (scrollTop >= floatTop && !this.data.isShowFloatTab) {
      this.setData({
        toTop: true,
        isShowFloatTab: true,
      });
    } else if (scrollTop < floatTop && this.data.isShowFloatTab) {
      this.setData({
        toTop: false,
        isShowFloatTab: false,
      });
    }
  },
  /**
   * 点击tab切换
   * @param  {[type]} event 
   * @return {[type]}       
   */
  clickTab: function(event) {
    var id = event.detail.id;
    this.data.curTabId = id;
    var isFirst = true;
    for (var i = 0; i < this.data.tabs.length; i++) {
      if (id == this.data.tabs[i].id) {
        isFirst = this.data.tabs[i].isFirst
        this.data.tabs[i].isSelect = true;
        this.data.tabs[i].isFirst = false;
      } else {
        this.data.tabs[i].isSelect = false;
      }
    }
    this.setData({
      tabs: this.data.tabs,
      curTabId: this.data.curTabId,
    });

    //更新数据，第一次点击时候加载重新加载数据
    if (isFirst) {
      this.getShopGoods();
    }
  },
  /*扫描二维码*/
  scanQRcode: function() {
    wx.scanCode({
      success: (res) => {
        console.log(res)
      }
    })
  },
  getData: function(params, cb) {
    wx.request({
      url: params._url,
      data: params.data,
      method: 'GET',
      header: {
        'content-type': 'application/json;charset=UTF-8'
      },
      success: function(res) {
        if (res.statusCode == 200) {
          typeof cb === 'function' && cb(res.data)
        }
      },
      fail: function() {},
      complete: function() {}
    })
  },
  // 滚动到顶部
  backTop: function () {
    // 控制滚动
    wx.pageScrollTo({
      scrollTop: 0
    })
  },

})